// 用来处理导航条
function FrontBase() {

}

FrontBase.prototype.run = function () {
    var self = this;
    self.listenAuthBoxHover();

};

FrontBase.prototype.listenAuthBoxHover = function () {
    var authBox = $(".auth-box");
    var userMoreBox = $(".user-more-box");
    // 鼠标hover事件
    authBox.hover(function () {
        userMoreBox.show();

    },function () {
        userMoreBox.hide();

    });
};


// 用来处理登录和注册的

function Auth() {
    var self = this;
    // 全局变量
    self.maskWrapper = $(".mask-wrapper");
    self.scrollWrapper = $(".scroll-wrapper");
    self.smsCaptcha = $(".sms_captcha-btn");

}

Auth.prototype.run = function () {
    var self = this;
    self.listenShowHideEvent();
    self.listenSwitchEvent();
    self.listenSigninEvent();
    self.listenImgCaptchaEvent();
    self.listenSmsCaptchaEvent();
    self.listenSignupEvent();


};

// 点击刷新验证码图片
Auth.prototype.listenImgCaptchaEvent = function(){
    var imgCaptcha = $(".img_captcha");
    imgCaptcha.click(function () {
        imgCaptcha.attr("src","/account/img_captcha/"+"?random="+Math.random())

    });
};
// 倒计时后 回位到发送验证码
Auth.prototype.smsSuccessEvent = function(){
    var self = this;
    messageBox.showSuccess("短信验证码发送成功！");
    self.smsCaptcha.addClass('disabled');
    var count = 10;
    // 解除元素绑定事件
    self.smsCaptcha.unbind("click");
    // 定时任务  倒计时
    var timer = setInterval(function () {
        self.smsCaptcha.text(count+"s");
        count --;
        if(count <= 0){
            clearInterval(timer);
            // 去除不可点元素
            self.smsCaptcha.removeClass("disabled");
            self.smsCaptcha.text("发送验证码");
            self.listenSmsCaptchaEvent();
        }
    },1000);
};
// 发送验证码 后 倒计时
Auth.prototype.listenSmsCaptchaEvent = function(){
    var self = this;
    // 发送验证码
    var smsCaptcha = $(".sms_captcha-btn");
    // 获取 注册 级别下的telephone
    // var telephoneInput = $(".signup-btn input[name='telephone']");
    var telephoneInput = $(".signup-group input[name='telephone']");
    smsCaptcha.click(function () {
        // 获取输入框手机号
        var telephone = telephoneInput.val();
        if(!telephone){
            messageBox.showInfo("请输入手机号码!")
        }
        xfzajax.get({
            "url" : "/account/sms_captcha/",
            "data": {
                "telephone" : telephone
            },
            "success" : function (result) {
                if(result["code"] == 200){
                     self.smsSuccessEvent();
                }

            },
            "fail" : function (error) {
                console.log(error)

            }
        });
    });
};


// 事件  登入/注册模态框显示
Auth.prototype.showEvent = function(){
    var self = this;
    self.maskWrapper.show();

};

Auth.prototype.hideEvent = function(){
    var self = this;
    self.maskWrapper.hide();

};

// 点击登入/登出事件
Auth.prototype.listenShowHideEvent = function(){
    var self = this;
    var signinBtn = $(".signin-btn");
    var signupBtn = $(".signup-btn");
    var closeBtn = $(".close-btn");

    signinBtn.click(function () {
        self.showEvent();
        self.scrollWrapper.css({"left":0});

    })
    signupBtn.click(function () {
        self.showEvent();
        self.scrollWrapper.css({"left":-400})

    })
    closeBtn.click(function () {
        self.hideEvent();
    })
};


Auth.prototype.listenSwitchEvent = function(){
    var self = this;
    var switcher = $(".switch");
    switcher.click(function () {
        var scrollLeft = self.scrollWrapper.css("left");
        // 因为scrollLeft 是带有PX 的值  要解析成整形
        surrenLeft = parseInt(scrollLeft);
        // 无过渡效果

        // if(surrenLeft < 0){
        //     scrollWrapper.css({"left":"0"})
        // }else{
        //     scrollWrapper.css({"left":"-400px"})
        // }
        // 有过度效果
        if(surrenLeft < 0){
            self.scrollWrapper.animate({"left":"0"})
        }else{
            self.scrollWrapper.animate({"left":"-400px"})
        }
    });
};


// // 立即登入点击事件 有bug
// Auth.prototype.listenSigninEvent = function(){
//     var self = this;
//     // 区分对待input 登入 和 注册 避免混淆
//     var signinGroup = $(".signin-group");
//     var telephoneInput = signinGroup.find("input[name='telephone']");
//     var passwordInput = signinGroup.find("input[name='password']");
//     var rememberInput = signinGroup.find("input[name='remember']");
//
//     // 点击立即登入时 获取数据
//     var submitBtn = signinGroup.find(".submit-btn");
//     submitBtn.click(function () {
//         // 获取数据
//         var telephone = telephoneInput.val();
//         var password = passwordInput.val();
//         // 选中事件 用 prop 选中返回True
//         var remember = rememberInput.prop("checked");
//
//         // ajax 数据交互
//         xfzajax.post({
//                 "url":"/account/login/",
//                 "data":{
//                     "telephone" : telephone,
//                     "password" : password,
//                     // 三目运算符
//                     "remember" : remember?1:0
//                 },
//                 "success":function (result) {
//
//                      // 隐藏 模态框
//                     self.hideEvent();
//                     // 刷新
//                     window.location.reload();
//                 }
//             });
//     });
//
// };


// 同上 ajax 报错传入result有bug
// Auth.prototype.listenSignupEvent = function(){
//     var signupGroup = $(".signup-group");
//     var submitBtn = signupGroup.find(".submit-btn");
//     submitBtn.click(function (event) {
//         // 默认传入的事件
//         // 阻止事件默认form提交
//         event.preventDefault();
//         var telephoneInput = signupGroup.find("input[name='telephone']");
//         var usernameInput = signupGroup.find("input[name='username']");
//         var imgCaptchaInput = signupGroup.find("input[name='img_captcha']");
//         var password1Input = signupGroup.find("input[name='password1']");
//         var password2Input = signupGroup.find("input[name='password2']");
//         var smsCaptchaInput = signupGroup.find("input[name='sms_captcha']");
//
//         var telephone = telephoneInput.val();
//         var username = usernameInput.val();
//         var img_captcha = imgCaptchaInput.val();
//         var password1 = password1Input.val();
//         var password2 = password2Input.val();
//         var sms_captcha = smsCaptchaInput.val();
//
//         xfzajax.post({
//             "url" : "/account/register/",
//             "data" : {
//                 'telephone': telephone,
//                 'username': username,
//                 'img_captcha': img_captcha,
//                 'password1': password1,
//                 'password2': password2,
//                 'sms_captcha': sms_captcha
//             },
//             "success" : function (result) {
//                 window.location.reload();
//             }
//         });
//     });
// };



// 立即登入点击事件
Auth.prototype.listenSigninEvent = function(){
    var self = this;
    // 区分对待input 登入 和 注册 避免混淆
    var signinGroup = $(".signin-group");
    var telephoneInput = signinGroup.find("input[name='telephone']");
    var passwordInput = signinGroup.find("input[name='password']");
    var rememberInput = signinGroup.find("input[name='remember']");

    // 点击立即登入时 获取数据
    var submitBtn = signinGroup.find(".submit-btn");
    submitBtn.click(function () {
        // 获取数据
        var telephone = telephoneInput.val();
        var password = passwordInput.val();
        // 选中事件 用 prop 选中返回True
        var remember = rememberInput.prop("checked");

        // ajax 数据交互
        xfzajax.post({
                "url":"/account/login/",
                "data":{
                    "telephone" : telephone,
                    "password" : password,
                    // 三目运算符
                    "remember" : remember?1:0
                },
                "success":function (result) {
                    console.log("=================")
                    console.log(result)
                    console.log("=================")
                    if(result['code'] === 200){
                        // 隐藏 模态框
                        self.hideEvent();
                        // 刷新
                        window.location.reload();
                    }else{
                        var messageObject = result['message'];
                        if(typeof messageObject == "string" || messageObject.constructor == String){
                            window.messageBox.show(messageObject);
                        }else{
                            // {"password":['密码最大长度不能超过20为！','xxx'],"telephone":['xx','x']}
                            for(var key in messageObject){
                                var message = messageObject[key];
                                var message = message[0];
                                window.messageBox.show(message);
                            }
                        }

                    }
                },
                "fail":function (error) {
                    console.log(error);
                    window.messageBox.showError('服务器内部错误！');
                }
            }
        )

    })

};

// 为重写报错  注册
Auth.prototype.listenSignupEvent = function(){
    var signupGroup = $(".signup-group");
    var submitBtn = signupGroup.find(".submit-btn");
    submitBtn.click(function (event) {
        // 默认传入的事件
        // 阻止事件默认form提交
        event.preventDefault();
        var telephoneInput = signupGroup.find("input[name='telephone']");
        var usernameInput = signupGroup.find("input[name='username']");
        var imgCaptchaInput = signupGroup.find("input[name='img_captcha']");
        var password1Input = signupGroup.find("input[name='password1']");
        var password2Input = signupGroup.find("input[name='password2']");
        var smsCaptchaInput = signupGroup.find("input[name='sms_captcha']");

        var telephone = telephoneInput.val();
        var username = usernameInput.val();
        var img_captcha = imgCaptchaInput.val();
        var password1 = password1Input.val();
        var password2 = password2Input.val();
        var sms_captcha = smsCaptchaInput.val();

        xfzajax.post({
            "url" : "/account/register/",
            "data" : {
                'telephone': telephone,
                'username': username,
                'img_captcha': img_captcha,
                'password1': password1,
                'password2': password2,
                'sms_captcha': sms_captcha
            },
            "success":function (result) {
                    console.log("=================")
                    console.log(result)
                    console.log("=================")
                    if(result['code'] === 200){
                        // 隐藏 模态框
                        // self.hideEvent();
                        // 刷新
                        window.location.reload();
                    }else{
                        var messageObject = result['message'];
                        if(typeof messageObject == "string" || messageObject.constructor == String){
                            window.messageBox.show(messageObject);
                        }else{
                            // {"password":['密码最大长度不能超过20为！','xxx'],"telephone":['xx','x']}
                            for(var key in messageObject){
                                var message = messageObject[key];
                                var message = message[0];
                                window.messageBox.show(message);
                            }
                        }

                    }
                },
            "fail":function (error) {
                    console.log(error);
                    window.messageBox.showError('服务器内部错误！');
                }
        });
    });
};


$(function () {
    var auth = new Auth();
    auth.run();

});

$(function () {
    var frontBase = new FrontBase();
    frontBase.run();
});

$(function () {
    if(window.template){
        template.defaults.imports.timeSince = function (dateValue) {
            var date = new Date(dateValue);
            var datets = date.getTime();  // 得到的是毫秒的
            var nowts = (new Date().getTime()); // 得到的是当前的时间戳
            var timestamp = (nowts- datets)/1000 //除以1000 得到的是秒
            if(timestamp < 60){
                return "刚刚";
            }
            else if(timestamp >= 60 && timestamp < 60*60){
                minutes = parseInt(timestamp / 60);
                return minutes + "分钟前";
            }
            else if(timestamp >= 60*60 && timestamp < 60*60*24){
                hours = parseInt(timestamp / 60 / 60);
                return hours + "小时前";
            }
            else if(timestamp >=60*60*24 && timestamp < 60*60*24*30){
                days = parseInt(timestamp / 60 / 60 / 24);
                return days + "天前";
            }else{
                var year = date.getFullYear();
                var month = date.getMonth();
                var day = date.getDay();
                var hour = date.getHours();
                var minute = date.getMinutes();
                return year+'/'+month+'/'+day+'/'+' '+hour+":"+minute;

            }
        }
    }
});